/*
COPYRIGHT (C) 2008 EPISERVER AB

THIS FILE IS PART OF WIKIX.
WIKIX IS FREE SOFTWARE: YOU CAN REDISTRIBUTE IT AND/OR MODIFY IT UNDER THE TERMS OF THE GNU LESSER GENERAL PUBLIC LICENSE VERSION v2.1 AS PUBLISHED BY THE FREE SOFTWARE FOUNDATION.

WIKIX IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU LESSER GENERAL PUBLIC LICENSE FOR MORE DETAILS.
YOU SHOULD HAVE RECEIVED A COPY OF THE GNU LESSER GENERAL PUBLIC LICENSE ALONG WITH WIKIX. IF NOT, SEE <HTTP://WWW.GNU.ORG/LICENSES/>.
*/

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using System.Text;
using EPiServer.Web.Hosting;
using System.Linq;
using EPiServer.Research.Wiki.Core;

namespace EPiServer.Research.Wiki.Units
{
    public partial class SectionEdit : EPiServer.UserControlBase
    {
        public bool IsArticle { get; set; }

        private const string images = ".png,.jpg,.gif,.jpeg";

        public string ConstructTinyScript()
        {
            //Make list of images and files
            bool hasItems = false;
            UnifiedDirectory ud = WikiManager.Instance.GetWikiArticle(CurrentPage).GetPageDirectory(false);
            string f = "[]";
            string i = "[]";
            if (ud != null)
            {
                string[] files = ud.GetFiles()
                    .Where(ff => images.IndexOf(System.IO.Path.GetExtension(ff.Name).ToLower()) == -1)
                    .Select(uf => uf.Name).ToArray();

                string[] imgs = ud.GetFiles()
                    .Where(ff => images.IndexOf(System.IO.Path.GetExtension(ff.Name).ToLower()) > -1)
                    .Select(uf => uf.Name).ToArray();
                if (files.Length > 0)
                {
                    f = "[";
                    foreach (string ff in files)
                    {
                        f += "{title:'" + ff + "', onclick:function(){insertContent('[[file:" + ff + "]]');}},";
                    }
                    f = f.TrimEnd(',');
                    f += "]";
                    hasItems = true;
                }
                if (imgs.Length > 0)
                {
                    i = "[";
                    foreach (string ii in imgs)
                    {
                        i += "{title:'" + ii + "', onclick:function(){insertContent('[[image:" + ii + "]]');}},";
                    }
                    i = i.TrimEnd(',');
                    i += "]";
                    hasItems = true;
                }
            }
            string iconLocation = EPiServer.Configuration.Settings.Instance.SiteUrl.AbsoluteUri + "EPiServer.Research.Wiki/img/document_attachment.png";
            string filetxt = Translate("/wiki/edit/filetext");
            string imgtxt = Translate("/wiki/edit/imgtext");
            StringBuilder sb = new StringBuilder();
            //Call a method that will add a file/image selector to the Tiny MCE editor
            if (hasItems) sb.Append("PrepareTinyPlugin(" + i + "," + f + ",'" + iconLocation + "','" + filetxt + "','" + imgtxt + "');");
            //Init the Tiny MCE editor
            //  sb.Append("tinyMCE.init({mode: 'textareas', theme_advanced_toolbar_location : 'top', theme_advanced_toolbar_align : 'left', theme_advanced_resizing : 'true', entity_encoding : \"utf-8\", theme: 'advanced', plugins:'table, -wikifile', theme_advanced_disable:'formatselect,fontselect,fontsizeselect,styleselect,anchor,code,cleanup,charmap,removeformat,help,hr,sub,sup,visualaid,separator,link,unlink', theme_advanced_buttons1_add:'insertbutton', theme_advanced_buttons3:'tablecontrols' });");



            if (!string.IsNullOrEmpty(Request["edit"]))
                sb.Append("function DoCallBack(){")
                    .Append("$.getJSON(\"" + this.CurrentPage.LinkURL + "&editCallback=" + Request["edit"] + "\", function(result) {});")
                    .Append("setTimeout ( \"DoCallBack()\", 20000 );")
                    .Append("}")
                    .Append("setTimeout(\"DoCallBack()\",20000);"); //Setup callbacks



            return sb.ToString();
        }

        protected PageData ActivePage;

        protected void Page_Load(object sender, EventArgs e)
        {

             (Page as TemplatePage).RegisterScriptFile("~/EPiServer.Research.Wiki/tiny_mce/tiny_mce3211/tiny_mce.js");
            
            (Page as TemplatePage).RegisterScriptFile(EPiServer.UriSupport.ResolveUrlFromUIBySettings("Javascript/system.js"));
            (Page as TemplatePage).RegisterScriptFile(EPiServer.UriSupport.ResolveUrlFromUIBySettings("Javascript/system.aspx"));
            (Page as TemplatePage).RegisterScriptFile(EPiServer.UriSupport.ResolveUrlFromUtilBySettings("Javascript/episerverscriptmanager.js"));
        
          
         
            string open = ConstructTinyScript();
            Page.ClientScript.RegisterStartupScript(this.GetType(), "SetupTinyMCE",
          open// old: "tinyMCE.init({ mode: 'exact', elements: '"+BodyText.ClientID+"', theme: 'simple' });"
                , true
                );




            if (!string.IsNullOrEmpty(Request["edit"]))
            {
                if ((GetPage(PageReference.Parse(Request["edit"])).PageTypeName == WikiManager.WIKIARTICLENAME) ||
                    (GetPage(PageReference.Parse(Request["edit"])).PageTypeName == WikiManager.WIKIROOTNAME)) IsArticle = true;
                else IsArticle = false;
            }
            if (!IsPostBack && !string.IsNullOrEmpty(Request["edit"]))
            {
                PageData pd = GetPage(PageReference.Parse(Request["edit"]));
                ActivePage = pd;
                EditName.Text = pd.PageName;
                BodyText.Text = (string)pd["MainBody"];
                EditShowTOC.Checked = (pd.PageTypeName == WikiManager.WIKIARTICLENAME && pd["ShowTOC"] != null);
                TypeList.Items.FindByValue((string)pd["Style"] ?? "Section").Selected = true;

                //Lock page for editing, TODO: Handle if no lock can be given
                if (!EditManager.Instance.GetLock(pd.PageLink))
                {
                    Response.Redirect(pd.LinkURL, true);
                }
            }
            else if (!IsPostBack && (HttpContext.Current.Items["ArticleName"] != null))
            {
                EditName.Text = Server.UrlDecode(HttpContext.Current.Items["ArticleName"].ToString());
            }

            if (!IsPostBack)
            {
                if (IsArticle) PopulateCategories();
                this.DataBind();
            }

       
        }

        public void CancelBtn_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request["edit"])) EditManager.Instance.ReleaseLock(PageReference.Parse(Request["edit"]));
            Response.Redirect(CurrentPage.LinkURL);
        }


        public void SaveBtn_Click(object sender, EventArgs e)
        {
            //TODO: Save Categories
            if (!string.IsNullOrEmpty(Request["edit"]))
            {
                PageReference pr = PageReference.Parse(Request["edit"]);
                //Edited article or section
                if (IsArticle)
                {
                    WikiManager.Instance.UpdateArticle(pr, EditName.Text, BodyText.Text, EditComment.Text, EditShowTOC.Checked, GetSelectedCategories());
                }
                else
                {
                    WikiManager.Instance.UpdateSection(pr, EditName.Text, TypeList.SelectedValue, BodyText.Text, EditComment.Text);
                }
                EditManager.Instance.ReleaseLock(pr);
                Response.Redirect(GetPage(pr).LinkURL);

            }
            else if (!string.IsNullOrEmpty(Request["add"]))
            {
                PageReference pr = PageReference.Parse(Request["add"]); //Add below this
                PageReference newS = WikiManager.Instance.CreateNewSection(pr, EditName.Text, TypeList.SelectedValue, BodyText.Text, EditComment.Text, pr);
                Response.Redirect(GetPage(newS).LinkURL);
            }
            else if (IsArticle)
            {
                //New article created
                //TODO: Validate
                //Save it
                PageReference pr = WikiManager.Instance.CreateNewArticle(CurrentPage.PageLink, EditName.Text, BodyText.Text, EditComment.Text, (string)HttpContext.Current.Items["ArticleName"], EditShowTOC.Checked, GetSelectedCategories());


                //Redirect to page
                Response.Redirect(GetPage(pr).LinkURL);
            }
        }




        protected void PopulateCategories()
        {
            var cats = (WikiManager.Instance.GetWikiRoot(CurrentPage.PageLink)["WikiCategories"] as CategoryList);
            if (cats == null) return;
            var res = cats
                .Select(id => (new ListItem() { Text = Category.Find(id).Name, Selected = (ActivePage == null) ? false : ActivePage.Category.MemberOf(id), Value = id.ToString() }))
                .OrderBy(li => li.Text)
                .ToArray();
            EditCategories.Items.Clear();
            EditCategories.Items.AddRange(res);
        }


    

        private int[] GetSelectedCategories()
        {
            List<int> rt = new List<int>();
            foreach (ListItem li in EditCategories.Items)
            {
                if (li.Selected) rt.Add(int.Parse(li.Value));
            }
            return rt.ToArray();
        }

        protected bool HasCategories()
        {
            var cats = (WikiManager.Instance.GetWikiRoot(CurrentPage.PageLink)["WikiCategories"] as CategoryList);
            if (cats == null) return false;
            if (cats.Count == 0) return false;
            return true;

        }

        //public void SaveBtn_Click(object sender, EventArgs e)
        //{

        ////TODO: Save Categories
        //    if (!string.IsNullOrEmpty(Request["edit"])) 
        //    {
        //        PageReference pr=PageReference.Parse(Request["edit"]);
        //        //Edited article or section
        //        if (IsArticle)
        //        {
        //            WikiManager.Instance.UpdateArticle(pr, EditName.Text, BodyText.Text, EditComment.Text,EditShowTOC.Checked,GetSelectedCategories());
        //        }
        //        else
        //        {
        //            WikiManager.Instance.UpdateSection(pr, EditName.Text, TypeList.SelectedValue, BodyText.Text, EditComment.Text);
        //        }
        //        EditManager.Instance.ReleaseLock(pr);
        //        Response.Redirect(GetPage(pr).LinkURL);

        //    }
        //    else if (!string.IsNullOrEmpty(Request["add"]))
        //    {
        //        PageReference pr = PageReference.Parse(Request["add"]); //Add below this
        //        PageReference newS=WikiManager.Instance.CreateNewSection(pr, EditName.Text, TypeList.SelectedValue, BodyText.Text, EditComment.Text, pr);
        //        Response.Redirect(GetPage(newS).LinkURL);
        //    }
        //    else if (IsArticle)
        //    {
        //        //New article created
        //        //TODO: Validate
        //        //Save it
        //        PageReference pr = WikiManager.Instance.CreateNewArticle(CurrentPage.PageLink, EditName.Text, BodyText.Text, EditComment.Text, (string)HttpContext.Current.Items["ArticleName"],  EditShowTOC.Checked, GetSelectedCategories());


        //        //Redirect to page
        //        Response.Redirect(GetPage(pr).LinkURL);
        //    }
        //}


    }
}
